#ifndef _WORKER_ACCEPTOR_H_
#define _WORKER_ACCEPTOR_H_

#include "Include.h"
#include "Socket.h"
#include "Settings.h"
#include <queue>


class AgentWorker : public SocketWorker
{

public:

	static std::vector<_JOB_INFO> g_JobList;
	static ACE_Thread_Mutex	g_JobLock;	


	static std::vector<AgentWorker *> g_VecAgent; 
	static ACE_Thread_Mutex	g_AgentLock;	



	ACE_Thread_Mutex m_workerLock;
	std::vector<_JOB_INFO> m_vecWorks;	
	std::vector<_JOB_INFO> m_vecReservedJob; 


	static bool IsAgentSlotFull();
	static bool IsDuplicatedAddr(const std::string& addr);

	static bool AddAgent(AgentWorker * agent);
	static bool DelAgent(AgentWorker * agent);
	static void CheckAgentState();					
	static void GetJobList();		
	static void PushCanceledJobs(const std::vector<_JOB_INFO>& vecCancel); 

	AgentWorker()
	{
		m_nAgentCpu = 0;
		m_nCheckCount = 0;

	}

	~AgentWorker()
	{

		if(DelAgent(this))
			printf("delete agentworker\n");

	}



private:


	bool DistJobs();
	int m_nAgentCpu;

public:

	static _JOB_INFO FetchJob(); 

	int GetMaxWorkCount()
	{
		int count = m_nAgentCpu * Settings::GetSettings()->RENDERER_CPU_MULTIPLE;

		if(count <= 0)
			count = 1;
		return count;
	}

	int m_nCheckCount;


	virtual bool Execute(const std::string &rcv_text);

	

	bool IsWorking(const std::string& job_id);
	bool AddWork();
	int GetSpareCount();
	int GetWorkCount();
	int GetReservedCount();
	int SendReadSetting();


	bool FinishWork(const std::string& job_id);
	bool DelReservedJobs(const Json::Value& root);


	static AgentWorker * GetRichestWorker();
	static int GetTotalSpareCount(); 
	static int GetTotalWorkCount(); 
	static int GetAgentCount(); 
	static bool SendAllReadSetting();

public:

	virtual int handle_close (ACE_HANDLE h, ACE_Reactor_Mask mask);
};

class GetJobThread : public ACE_Task<ACE_MT_SYNCH>
{
public:
	bool stop;
	GetJobThread()
	{
		stop = false;
	}

	~GetJobThread()
	{
		stop = true;
		this->wait();
	}


	int svc(void);

};



class SettingCheckThread : public ACE_Task<ACE_MT_SYNCH>
{
public:
	bool stop;
	SettingCheckThread()
	{
		stop = false;
	}

	~SettingCheckThread()
	{
		stop = true;
		this->wait();
	}


	int svc(void);
	void CheckControllerTime();

};





class AcceptHandler : public ACE_Event_Handler {

    private:

        ACE_Reactor *mReactor;

        ACE_SOCK_Acceptor mAcceptor;

    public:

        AcceptHandler(ACE_Reactor *reactor = 0);
        virtual ~AcceptHandler();

        int open(void);

        virtual ACE_HANDLE get_handle(void) const;

        virtual int handle_input(ACE_HANDLE = ACE_INVALID_HANDLE);

        virtual int handle_close(ACE_HANDLE, ACE_Reactor_Mask);

};



#endif 
